package com.elong.android.specialhouse.push;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.elong.android.specialhouse.AppConstants;
import com.elong.android.specialhouse.JSONConstants;
import com.elong.android.specialhouse.R;
import com.elong.android.specialhouse.activity.ChatActivity;
import com.elong.android.specialhouse.activity.HomeActivity;
import com.elong.android.specialhouse.entity.ImPushPayloadContent;
import com.elong.android.specialhouse.entity.PushContent;
import com.elong.android.specialhouse.notification.BasicNotificationBuilder;
import com.elong.android.specialhouse.notification.MyNotificationManager;
import com.elong.android.specialhouse.utils.PrefUtils;
import com.elong.android.specialhouse.utils.Utils;
import com.igexin.sdk.PushConsts;
import com.igexin.sdk.PushManager;

public class PushReceiver extends BroadcastReceiver {

    public static final String ACTION_GET_MESSAGE = "com.elong.android.apartment.push.getmessage";
    public static final String ACTION_GET_CID_SUCCESS = "com.elong.android.apartment.push.getcid";
    public static final String KEY_CLIENT_ID = "cid";

    /**
     * 应用未启动, 个推 service已经被唤醒,保存在该时间段内离线消息(此时 GetuiSdkDemoActivity.tLogView == null)
     */
    public StringBuilder payloadData = new StringBuilder();

    @Override
    public void onReceive(final Context context, final Intent intent) {

        Bundle bundle = intent.getExtras();
        Log.d("PushReceiver", "onReceive() action=" + bundle.getInt("action"));
        switch (bundle.getInt(PushConsts.CMD_ACTION)) {
            case PushConsts.GET_MSG_DATA:
                // 获取透传数据
                // String appid = bundle.getString("appid");
                byte[] payload = bundle.getByteArray("payload");
                String taskid = bundle.getString("taskid");
                String messageid = bundle.getString("messageid");
                // smartPush第三方回执调用接口，actionid范围为90000-90999，可根据业务场景执行
                boolean result = PushManager.getInstance().sendFeedbackMessage(context, taskid, messageid, 90001);
//                System.out.println("第三方回执接口调用" + (result ? "成功" : "失败"));
                if (payload != null) {
                    String data = new String(payload);
                    Log.d("PushReceiver", "receiver payload : " + data);
                    payloadData.append(data);
                    // name = "msgType" 消息类型 0：订单通知，1：结算通知， 2：系统通知，3：一对一消息
                    try {
                        JSONObject content = JSONObject.parseObject(payloadData.toString());
                        if (content.containsKey(JSONConstants.ATTR_MSG_TYPE)) {
                            int msgType = content.getIntValue(JSONConstants.ATTR_MSG_TYPE);
                            if (msgType > 2) { //一对一消息
                                ImPushPayloadContent payloadContent = JSONObject.parseObject(content.getString(JSONConstants.ATTR_TRANSMISSION_CONTENT), ImPushPayloadContent.class);
                                sendIMMessage(context, payloadContent);
                            } else {  //其它类型的消息
                                String title = content.getString(JSONConstants.ATTR_TITLE);
                                try {
                                    PushContent pushContent = JSON.parseObject(content.getString(JSONConstants.ATTR_TRANSMISSION_CONTENT), PushContent.class);
                                    if (pushContent != null) {
                                        sendSystemMessage(context, title, pushContent.title + "  " + pushContent.desc);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                break;

            case PushConsts.GET_CLIENTID:
                // 获取ClientID(CID)
                // 第三方应用需要将CID上传到第三方服务器，并且将当前用户帐号和CID进行关联，以便日后通过用户帐号查找CID进行消息推送
                String cid = bundle.getString("clientid");
                Log.i("save", "cid----> " + cid);
                PrefUtils.setClientId(context, cid);
                Intent getCidSuccess = new Intent();
                getCidSuccess.putExtra(KEY_CLIENT_ID, cid);
                getCidSuccess.setAction(ACTION_GET_CID_SUCCESS);
                context.sendBroadcast(getCidSuccess);
                break;

            case PushConsts.THIRDPART_FEEDBACK:
                /*
                 * String appid = bundle.getString("appid"); String taskid =
                 * bundle.getString("taskid"); String actionid = bundle.getString("actionid");
                 * String result = bundle.getString("result"); long timestamp =
                 * bundle.getLong("timestamp");
                 * 
                 * Log.d("GetuiSdkDemo", "appid = " + appid); Log.d("GetuiSdkDemo", "taskid = " +
                 * taskid); Log.d("GetuiSdkDemo", "actionid = " + actionid); Log.d("GetuiSdkDemo",
                 * "result = " + result); Log.d("GetuiSdkDemo", "timestamp = " + timestamp);
                 */
                break;

            default:
                break;
        }
    }

    /**
     * 发送一对一消息的推送
     *
     * @param context
     * @param content
     */
    private void sendIMMessage(final Context context, ImPushPayloadContent content) {
        if (!Utils.isAppRunning(context) || !ChatActivity.isForground) {//判断是否需要发送Notification
            PrefUtils.setIfHaveNewMessage(context, true);
            BasicNotificationBuilder builder = new BasicNotificationBuilder(context, new BasicNotificationBuilder.GetPendingIntent() {
                @Override
                public PendingIntent getPendingIntent() {
                    Intent toHome = new Intent(context, HomeActivity.class);
                    PendingIntent contentIntent = PendingIntent.getActivity(context, 0, toHome, PendingIntent.FLAG_CANCEL_CURRENT);
                    return contentIntent;
                }
            });
            MyNotificationManager.getInstanse().setNotificationInterface(builder);
            MyNotificationManager.getInstanse().sendNotification(context, content.senderName, "发来一条消息", R.drawable.ic_launcher);
        }
        Intent action = new Intent();
        action.putExtra(AppConstants.KEY_PAYLOAD, content);
        action.setAction(ACTION_GET_MESSAGE);
        context.sendOrderedBroadcast(action, null);
    }

    private void sendSystemMessage(final Context context, String title, String text) {
        PrefUtils.setIfHaveNewMessage(context, true);
        BasicNotificationBuilder builder = new BasicNotificationBuilder(context, new BasicNotificationBuilder.GetPendingIntent() {
            @Override
            public PendingIntent getPendingIntent() {
                Intent toHome = new Intent(context, HomeActivity.class);
                PendingIntent contentIntent = PendingIntent.getActivity(context, 0, toHome, PendingIntent.FLAG_CANCEL_CURRENT);
                return contentIntent;
            }
        });
        MyNotificationManager.getInstanse().setNotificationInterface(builder);
        MyNotificationManager.getInstanse().sendNotification(context, title, text, R.drawable.ic_launcher);
        Intent action = new Intent();
//        action.putExtra(AppConstants.KEY_PAYLOAD, content);
        action.setAction(ACTION_GET_MESSAGE);
        context.sendOrderedBroadcast(action, null);
    }
}
